/**
 * 
 */
package com.highglass.videoplayer;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import com.highglass.videoplayer.subTitle.AliasUtil;
import com.highglass.videoplayer.subTitle.AssDecoder;
import com.highglass.videoplayer.subTitle.SmiDecoder;
import com.highglass.videoplayer.subTitle.SrtDecoder;
import com.highglass.videoplayer.subTitle.SubDecoder;
import com.highglass.videoplayer.subTitle.SubTitleContent;
import com.highglass.videoplayer.subTitle.autodetect.AutoDetectUtil;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author hm
 *
 */
public class SubContentUtil {
	public static enum SubTitleType{
		srt,
		smi,
		ass,
		ssa,
		sub
	};
//	public final static String[] SUBTITLETYPESTR = new String[]{".srt", ".smi", ".ass", ".ssa", ".idx"};
	public final static String[] SUBTITLETYPESTR = new String[]{".srt", ".smi", ".ass", ".ssa"};
	public static int lastSubtitleIndex = -1;
	public static boolean stopDecodeFlag = false;

	public static String removeHtmlTag(String input){
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return str;
	}

	public static String[] getLocalSubTitleFiles(Context context,String path){
		File file = new File(path);
		if(file.exists()){
			List<String> list = getMLocalySubtitlefiles(file);
			String[] strs = new String[list.size()];
			for(int i = 0; i < strs.length; i++){
				strs[i] = list.get(i);
			}
			return strs;
		}else{
			return null;
		}
	}
	public static List getMLocalySubtitlefiles(File parent){
		List<String> fileList = new ArrayList<String>();
		File[] list = parent.listFiles();
		for(File file:list){
			if(!file.isHidden()&&file.length()>0){
					if(file.isDirectory()){
						fileList.addAll(getMLocalySubtitlefiles(file));
					}else{
						if((file.getAbsolutePath().contains(".srt")||file.getAbsolutePath().contains(".smi")||
								file.getAbsolutePath().contains(".ass")||file.getAbsolutePath().contains(".ssa"))){
							fileList.add(file.getAbsolutePath());
						}
					}
				}
		}
		return fileList;
	}
	public static String[] getSubTitleFiles(Context context,Uri uri){

		String videoFullPath = uri.getPath();

		if(videoFullPath == null)
			return null;
		File file = new File(videoFullPath);
		int index1 = videoFullPath.lastIndexOf(".");
		int index2 = videoFullPath.lastIndexOf("/");
		String name = (index1 == -1 ? videoFullPath.substring(index2):videoFullPath.substring(index2,index1)).replace("/","");

		if(file.exists()){
			File parent = file.getParentFile();
			List<String> list = getMySubtitlefiles(parent, name);
			if(list ==null)
				return null;
			String[] strs = new String[list.size()];
			for(int i = 0; i < strs.length; i++){
				strs[i] = list.get(i);
			}
			return strs;
		}else{
			return null;
		}
	}

	public static String getSubTitleFile(Context context, Uri uri){

		String videoFullPath = uri.getPath();

		if(videoFullPath == null)
			return null;
		File file = new File(videoFullPath);
		int index1 = videoFullPath.lastIndexOf(".");
		int index2 = videoFullPath.lastIndexOf("/");
		String name = (index1 == -1 ? videoFullPath.substring(index2):videoFullPath.substring(index2,index1)).replace("/","");

		if(file.exists()){
			File parent = file.getParentFile();
			return getMySubtitlefile(parent,name);
		}else{
			return null;
		}
	}

	public static List getMySubtitlefiles(File parent,String name){
		List<String> fileList = new ArrayList<String>();
		File[] list = parent.listFiles();
		for(File file:list){
			if(!file.isHidden()&&file.length()>0){
					if(file.isDirectory()){
//						fileList.addAll(getMySubtitlefiles(file, name));
					}else{
						if((file.getAbsolutePath().contains(".srt")||file.getAbsolutePath().contains(".smi")||
								file.getAbsolutePath().contains(".ass")||file.getAbsolutePath().contains(".ssa"))){
							fileList.add(file.getAbsolutePath());
						}
					}
			}
		}
		return fileList;
	}

	public static String getMySubtitlefile(File parent,String name){
		File[] list = parent.listFiles();
		if(list==null){
			return null;
		}
		for(File file:list){
				if(!file.isHidden()&&file.length()>0){
						if(file.isDirectory()){
//							return getMySubtitlefile(file,name);
						}else{
							if((file.getAbsolutePath().contains(".srt")||file.getAbsolutePath().contains(".smi")||
									file.getAbsolutePath().contains(".ass")||file.getAbsolutePath().contains(".ssa"))){
								return file.getAbsolutePath();
							}
						}
				}
		}
		return null;
	}
	public static Map<String, List<SubTitleContent>> decodeSubtitle(String subTitlePath){
		if(subTitlePath.toLowerCase().endsWith(".srt")){
			try {
				return new SrtDecoder().decodeSubTitle(subTitlePath,null);
			} catch (Exception e) {
				try {
					return new SrtDecoder().decodeSubTitle(subTitlePath,"ISO-8859-1");
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}else if(subTitlePath.toLowerCase().endsWith(".ass") || subTitlePath.toLowerCase().endsWith(".ssa")){
			try {
				return new AssDecoder().decodeSubTitle(subTitlePath,null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(subTitlePath.toLowerCase().endsWith(".smi")){
			try {
				return new SmiDecoder().decodeSubTitle(subTitlePath,null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(subTitlePath.toLowerCase().endsWith(".idx")){
			try {
				return new SubDecoder().decodeSubTitle(subTitlePath,null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return null;
	}
	
	public synchronized static SubTitleContent getCurrentSubTitle(int pos, final Map<String, List<SubTitleContent>> subtitleList){
		StringBuffer sb = null;
		if(subtitleList == null){
			return null;
		}
		Iterator<String> keyIt = subtitleList.keySet().iterator();
		String keyStr = null;
		List<SubTitleContent> contentList = null;
		SubTitleContent tmpcontent = null;
		SubTitleContent content = null;
		int searchIndex = 0;
		int searchStartIndex = 0;
		int searchEndIndex = 0;
		int loopCount = -1;
		
		while(keyIt.hasNext()){
			loopCount++;
			tmpcontent = null;
			keyStr = keyIt.next();
			contentList = subtitleList.get(keyStr);
//			Log.v("+++", "++++++++++++++++++++let me search :" + keyStr);
			if(contentList == null || contentList.size() == 0){
				continue;
			}
			
			if(sb != null && loopCount != 0){
//				sb.append("\n");
				lastSubtitleIndex = -1;
				
				searchIndex = 0;
				searchStartIndex = 0;
				searchEndIndex = 0;
			}
			
			//1.use last index to search
			try {
				tmpcontent = contentList.get(lastSubtitleIndex + 1);
//				Log.v("+++", "++++++++++++++++++++++++++++++++contentList[" + (lastSubtitleIndex + 1) + "]:" + tmpcontent.getmSubTitleLine());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				tmpcontent = contentList.get(0);
//				Log.v("+++", "++++++++++++++++++++++++++++++++content:" + tmpcontent.getmSubTitleLine());
			}
			
			int guessStarttime = tmpcontent.getmSubTitleStartTime();
			int guessEndtime = tmpcontent.getmSubTitleEndTime();
			
//			Log.v("+++", ")))))))))))))))))))guessStarttime:" + guessStarttime + " guessEndtime:" + guessEndtime);
			
			if(pos >= guessStarttime && pos <= guessEndtime){
				if(sb == null)
					sb = new StringBuffer("");
				else
					sb.append("<br>");
				if(tmpcontent.getmSubTitleLine() == null){
					tmpcontent.setmSubTitleBmp(BitmapFactory.decodeFile("/flash/" + tmpcontent.hashCode() + ".png"));
				}else{
					sb.append(tmpcontent.getmSubTitleLine());
				}
				
				content = tmpcontent.getSimpleCopy();
				lastSubtitleIndex++;
				int tryCount = 1;
				int lastIndex = 0;
				//scan forward
				while(true){
					try {
						tmpcontent = contentList.get(lastSubtitleIndex - tryCount);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						break;
					}
					if(tmpcontent.getmSubTitleStartTime() <= pos && tmpcontent.getmSubTitleEndTime() >= pos){
//						Log.v("+++", "Append :" + tmpcontent.getmSubTitleLine());
						sb.insert(0, tmpcontent.getmSubTitleLine() + "<br>");
//						sb.append("<br>" + tmpcontent.getmSubTitleLine());
					}
					
					tryCount++;
				}
				
				lastIndex = lastSubtitleIndex;
				lastSubtitleIndex = lastSubtitleIndex - tryCount + 1;
				
				tryCount = 1;
				//scan backward
				while(true){
					try {
						tmpcontent = contentList.get(lastIndex + tryCount);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						break;
					}
					if(tmpcontent.getmSubTitleStartTime() <= pos && tmpcontent.getmSubTitleEndTime() >= pos){
//						Log.v("+++", "Append :" + tmpcontent.getmSubTitleLine());
						sb.append("<br>" + tmpcontent.getmSubTitleLine());
					}else if(pos < tmpcontent.getmSubTitleStartTime()){
						break;
					}
					
					tryCount++;
				}
				
				lastSubtitleIndex = lastIndex + tryCount - 1;
				continue;
			}//2.guess fail
			else{
				searchStartIndex = 0;
				searchEndIndex = contentList.size() - 1;
				while(true){
					searchIndex = (searchStartIndex + searchEndIndex) / 2;
//					Log.v("+++", ">>>>>>>>>>>>>>>>>>>>searchIndex:" + searchIndex + " searchStartIndex:" + searchStartIndex + " searchEndIndex:" + searchEndIndex);
					if(searchEndIndex - searchStartIndex == 1){
						if(contentList.get(searchStartIndex).getmSubTitleStartTime() <= pos && contentList.get(searchStartIndex).getmSubTitleEndTime() >= pos)
							searchIndex = searchStartIndex;
						else if(contentList.get(searchEndIndex).getmSubTitleStartTime() <= pos && contentList.get(searchEndIndex).getmSubTitleEndTime() >= pos)
							searchIndex = searchEndIndex;
						else
							break;
					}else if(searchIndex == 0 && searchStartIndex == 0 && searchEndIndex == 0){
						if(contentList.get(0).getmSubTitleStartTime() <= pos && contentList.get(0).getmSubTitleEndTime() >= pos)
							searchIndex = 0;
						else
							break;
					}
					
					tmpcontent = null;
					try {
						tmpcontent = contentList.get(searchIndex);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						tmpcontent = null;
						break;
					}
//					if(contentList.get(searchStartIndex).getmSubTitleEndTime() < pos && contentList.get(searchEndIndex).getmSubTitleStartTime() > pos && (searchStartIndex - searchEndIndex) == 1)
//						break;
					
					if(tmpcontent.getmSubTitleEndTime() < pos){
						searchStartIndex = searchIndex;
						continue;
					}else if(tmpcontent.getmSubTitleStartTime() > pos){
						searchEndIndex = searchIndex;
						continue;
					}else if(tmpcontent.getmSubTitleStartTime() <= pos && tmpcontent.getmSubTitleEndTime() >= pos){
						if(sb == null)
							sb = new StringBuffer("");
						else
							sb.append("<br>");
//						sb.append(content.getmSubTitleLine());
						if(tmpcontent.getmSubTitleLine() == null){
							tmpcontent.setmSubTitleBmp(BitmapFactory.decodeFile("/flash/" + tmpcontent.hashCode() + ".png"));
						}else{
							sb.append(tmpcontent.getmSubTitleLine());
						}
							
						content = tmpcontent.getSimpleCopy();
						int tryCount = 1;
						int lastIndex = 0;
						//scan forward
						while(true){
							try {
								tmpcontent = contentList.get(searchIndex - tryCount);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								break;
							}
							if(tmpcontent.getmSubTitleStartTime() <= pos && tmpcontent.getmSubTitleEndTime() >= pos){
//								Log.v("+++", "Append :" + tmpcontent.getmSubTitleLine());
								sb.insert(0, tmpcontent.getmSubTitleLine() + "<br>");
//								sb.append("<br>" + tmpcontent.getmSubTitleLine());
							}
							
							tryCount++;
						}
						
						lastSubtitleIndex = searchIndex - tryCount + 1;
						
						tryCount = 1;
						//scan backward
						while(true){
							try {
								tmpcontent = contentList.get(searchIndex + tryCount);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								break;
							}
							if(tmpcontent.getmSubTitleStartTime() <= pos && tmpcontent.getmSubTitleEndTime() >= pos){
//								Log.v("+++", "Append :" + tmpcontent.getmSubTitleLine());
								sb.append("<br>" + tmpcontent.getmSubTitleLine());
							}else if(pos < tmpcontent.getmSubTitleStartTime()){
								break;
							}
							
							tryCount++;
						}
						
						lastSubtitleIndex = searchIndex + tryCount - 1;
						break;
					}
				}
			}
		}
		
//		Log.v("+++", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>end getCurrentSubTitle:sb=" + sb);
		if(sb != null){
			content.setmSubTitleLine(sb.toString());
			return content;
		}else 
			return null;
	}
	
	public static String encodeType = null;
	/**
	 * detect encode type
	 * @param subTitlePath
	 * @return InputStreamReader with encode deal
	 * @throws FileNotFoundException 
	 * @throws UnsupportedEncodingException 
	 */
	public static BufferedReader getEncodeType(String subTitlePath) throws FileNotFoundException, UnsupportedEncodingException{
		InputStream encodeinput = new FileInputStream(subTitlePath);
		BufferedInputStream encodebin = new BufferedInputStream(encodeinput);
		encodeType = AutoDetectUtil.detectEncode(6, encodebin);
		
		try {
			encodebin.close();
			encodebin = null;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//It seems unecessary
		try {
			encodeinput.close();
			encodeinput = null;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		InputStream in = new FileInputStream(subTitlePath);
		BufferedInputStream bin = new BufferedInputStream(in);
		Log.v("+++", ">>>>>>>>>>>>>>>>>>>>>>>encodeType: " + encodeType);
		InputStreamReader isr = null;
		
		if(encodeType != null && !"ascii".equals(encodeType)){
			if(subTitlePath.endsWith("srt") && encodeType.equals("windows-1252")){
				encodeType = "Unicode";
			}if(subTitlePath.endsWith("smi") && encodeType.equals("windows-1252")){
				encodeType = "GB2312";
			}else{
				encodeType = AliasUtil.getAlias(encodeType);
			}
			
			if("nomatch".equals(encodeType) || "Shift_JIS".equals(encodeType)){
				encodeType = "windows-1253";
			}
			
			isr = new InputStreamReader(bin, encodeType);
		}else{
			isr = new InputStreamReader(bin);
		}
		
		BufferedReader br = new BufferedReader(isr);
		return br;
	}
	
	public static BufferedReader getEncodeType(String subTitlePath,String encodeType) throws FileNotFoundException, UnsupportedEncodingException{
		InputStream in = new FileInputStream(subTitlePath);
		BufferedInputStream bin = new BufferedInputStream(in);
		Log.v("+++", ">>>>>>>>>>>>>>>>>>>>>>>encodeType: " + encodeType);
		InputStreamReader isr = null;
		
		if(encodeType != null && !"ascii".equals(encodeType)){	
			isr = new InputStreamReader(bin, encodeType);
		}else{
			isr = new InputStreamReader(bin);
		}
		
		BufferedReader br = new BufferedReader(isr);
		return br;
	}
	
	public static void SortAllList(Map<String, List<SubTitleContent>> subTitleMap){
		Set<String> keySet = subTitleMap.keySet();
		Iterator<String> keyIt = keySet.iterator();
		
		String key = null;
		List<SubTitleContent> subTitleList = null;
		while(keyIt.hasNext()){
			key = keyIt.next();
			subTitleList = subTitleMap.get(key);
			
			Collections.sort(subTitleList);
		}
	}

	public static void earlySubTime(String loadSubPath){
		try {
			BufferedReader reader = null;
			reader = new BufferedReader(new FileReader(new File(loadSubPath)));

			String line = null;

			// 一行一行的读
			StringBuilder sb = new StringBuilder();

			while ((line = reader.readLine()) != null) {
				if (line.contains("-->")) {
					String str1 = line.split("-->")[0].trim();
					String str2 = line.split("-->")[1].trim();
					String strHour1 = str1.substring(0, 2);
					String strHour2 = str2.substring(0, 2);
					String strMinute1 = str1.substring(3, 5);
					String strMinute2 = str2.substring(3, 5);
					String strSecond1 = str1.substring(6, 8);
					String strSecond2 = str2.substring(6, 8);
					String strMicosecond1 = str1.substring(9, 12);
					String strMicosecond2 = str2.substring(9, 12);
					int hour1 = Integer.parseInt(strHour1);
					int hour2 = Integer.parseInt(strHour2);
					int minute1 = Integer.parseInt(strMinute1);
					int minute2 = Integer.parseInt(strMinute2);
					int second1 = Integer.parseInt(strSecond1);
					int second2 = Integer.parseInt(strSecond2);
					int micosecond1 = Integer.parseInt(strMicosecond1);
					int micosecond2 = Integer.parseInt(strMicosecond2);
					int targetTime1 = hour1 * 3600000 + minute1 * '\uea60' + second1 * 1000 + micosecond1;
					int targetTime2 = hour2 * 3600000 + minute2 * '\uea60' + second2 * 1000 + micosecond2;
					long l1 = targetTime1 - 1000;
					long l2 = targetTime2 - 1000;
					SimpleDateFormat ttime = new SimpleDateFormat("HH:mm:ss,SS");
					String sTime1 = ttime.format(new Date(l1)).toString();
					String sTime2 = ttime.format(new Date(l2)).toString();
					String sPre1 = sTime1.substring(0, 2);
					String sPre2 = sTime2.substring(0, 2);
					StringBuilder sb1 = new StringBuilder(sTime1);
					StringBuilder sb2 = new StringBuilder(sTime2);
					sTime1 = sb1.replace(1,2,String.valueOf(Integer.parseInt(sPre1)-8)).toString();
					sTime2 = sb2.replace(1,2,String.valueOf(Integer.parseInt(sPre2)-8)).toString();
					String sEnd1 = sTime1.substring(9);
					String sEnd2 = sTime2.substring(9);
					StringBuilder sbb1 = new StringBuilder(sEnd1);
					StringBuilder sbb2 = new StringBuilder(sEnd2);
					String[] strs1 = sTime1.split(",");
					String[] strs2 = sTime2.split(",");
					StringBuilder sbbb1 = new StringBuilder(strs1[0]);
					StringBuilder sbbb2 = new StringBuilder(strs2[0]);
					if(sEnd1.length() == 2){
						sEnd1 = sbb1.insert(0,",0").toString();
						sTime1 = sbbb1.append(sEnd1).toString();
					}
					if(sEnd2.length() == 2){
						sEnd2 = sbb2.insert(0,",0").toString();
						sTime2 = sbbb2.append(sEnd2).toString();
					}
					line = sTime1 + " --> " + sTime2;
					System.out.println("line = " + line);
				}
				sb.append(line);
				sb.append("\r\n");
			}
			reader.close();

			//写回去
			RandomAccessFile mm = new RandomAccessFile(new File(loadSubPath), "rw");
			mm.writeBytes(sb.toString());
			mm.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void earlySubTimee(String loadSubPath){
		try {
			FileReader fr = new FileReader(new File(loadSubPath));
			BufferedReader br=new BufferedReader(fr);
			String data = null;
			while ((data = br.readLine()) != null){
				if(data.contains("-->")){
					String str1 = data.split("-->")[0].trim();
					String str2 = data.split("-->")[1].trim();
					String strHour1 = str1.substring(0, 2);
					String strHour2 = str2.substring(0, 2);
					String strMinute1 = str1.substring(3, 5);
					String strMinute2 = str2.substring(3, 5);
					String strSecond1 = str1.substring(6, 8);
					String strSecond2 = str2.substring(6, 8);
					String strMicosecond1 = str1.substring(9, 12);
					String strMicosecond2 = str2.substring(9, 12);
					int hour1 = Integer.parseInt(strHour1);
					int hour2 = Integer.parseInt(strHour2);
					int minute1 = Integer.parseInt(strMinute1);
					int minute2 = Integer.parseInt(strMinute2);
					int second1 = Integer.parseInt(strSecond1);
					int second2 = Integer.parseInt(strSecond2);
					int micosecond1 = Integer.parseInt(strMicosecond1);
					int micosecond2 = Integer.parseInt(strMicosecond2);
					int targetTime1 = hour1 * 3600000 + minute1 * '\uea60' + second1 * 1000 + micosecond1;
					int targetTime2 = hour2 * 3600000 + minute2 * '\uea60' + second2 * 1000 + micosecond2;
					long l1 = targetTime1 - 1000;
					long l2 = targetTime2 - 1000;
					SimpleDateFormat ttime = new SimpleDateFormat("HH:mm:ss,SS");
					String sTime1 = ttime.format(new Date(l1)).toString();
					String sTime2 = ttime.format(new Date(l2)).toString();
					String sPre1 = sTime1.substring(0, 2);
					String sPre2 = sTime2.substring(0, 2);
					StringBuilder sb1 = new StringBuilder(sTime1);
					StringBuilder sb2 = new StringBuilder(sTime2);
					sTime1 = sb1.replace(1,2,String.valueOf(Integer.parseInt(sPre1)-8)).toString();
					sTime2 = sb2.replace(1,2,String.valueOf(Integer.parseInt(sPre2)-8)).toString();
					String sEnd1 = sTime1.substring(9);
					String sEnd2 = sTime2.substring(9);
					StringBuilder sbb1 = new StringBuilder(sEnd1);
					StringBuilder sbb2 = new StringBuilder(sEnd2);
					String[] strs1 = sTime1.split(",");
					String[] strs2 = sTime2.split(",");
					StringBuilder sbbb1 = new StringBuilder(strs1[0]);
					StringBuilder sbbb2 = new StringBuilder(strs2[0]);
					if(sEnd1.length() == 2){
						sEnd1 = sbb1.insert(0,",0").toString();
						sTime1 = sbbb1.append(sEnd1).toString();
					}
					if(sEnd2.length() == 2){
						sEnd2 = sbb2.insert(0,",0").toString();
						sTime2 = sbbb2.append(sEnd2).toString();
					}
					String sTime = sTime1 + " --> " + sTime2;
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将文件中指定内容的第一行替换为其它内容.
	 *
	 * @param oldStr
	 *            查找内容
	 * @param replaceStr
	 *            替换内容
	 */
	public static void replaceTxtByStr(String path,String oldStr,String replaceStr) {
		String temp = "";
		try {
			File file = new File(path);
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			StringBuffer buf = new StringBuffer();

			// 保存该行前面的内容
			for (int j = 1; (temp = br.readLine()) != null
					&& !temp.contains(oldStr); j++) {
				buf = buf.append(temp);
				buf = buf.append(System.getProperty("line.separator"));
			}

			// 将内容插入
			buf = buf.append(replaceStr);

			// 保存该行后面的内容
			while ((temp = br.readLine()) != null) {
				buf = buf.append(System.getProperty("line.separator"));
				buf = buf.append(temp);
			}

			br.close();
			FileOutputStream fos = new FileOutputStream(file);
			PrintWriter pw = new PrintWriter(fos);
			pw.write(buf.toString().toCharArray());
			pw.flush();
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
